package lelouet.sh3d.plugins.sweetDatacenter.gui;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * abstract class for [label:JTextfield] JPanel that requires to be specified
 * what to do when text is entered.<br />
 * Override {@link #onValidation(String)} to specify required behaviour<br />
 * This method is invoked when the {@link JTextField} loses focus or when
 * "enter" key is used<br />
 * the text in the field can be modified by calling {@link #setText(String)}
 */
public abstract class ATextFieldValidation extends JPanel {

	private static final long serialVersionUID = 1L;

	protected JLabel label;
	protected JTextField field;

	public ATextFieldValidation(String name, int labelWidth, int fieldWidth,
			int height) {
		setLayout(new FlowLayout(FlowLayout.LEFT));
		label = new JLabel(name);
		label.setPreferredSize(new Dimension(labelWidth, height));
		add(label);
		field = new JTextField();
		field.setPreferredSize(new Dimension(fieldWidth, height));
		field.addFocusListener(new FocusListener() {

			@Override
			public void focusLost(FocusEvent e) {
				onValidation(field.getText());
			}

			@Override
			public void focusGained(FocusEvent e) {
			}
		});
		field.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				onValidation(field.getText());
			}
		});
		add(field);
	}

	public void setText(String text) {
		field.setText(text);
	}

	public abstract void onValidation(String text);
}
